package com.bbcare.followup.plat.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.service.IReserveService;


/**
 * 预约排程业务。
 */
@Controller
@RequestMapping("/reserve")
public class ReservationController {
    private final static Logger logger = Logger.getLogger(ReservationController.class);

    @Autowired
    private IReserveService reserveService;


    /**
     * 查询最近2周内的治疗仪预约情况。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_machine_reservation")
    public ResultModel queryMachineSchedule(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryMachineSchedule() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId   = (String) sessionMap.get("tenantId");

        return new ResultModel<>(reserveService.queryAvailableReservation());
    }

    /**
     * 治疗仪下约。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/make_machine_reservation")
    public ResultModel makeMachineReservation(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++makeMachineReservation() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer reservationId = jsonData.getInteger("reservation_id");
        final String patientId  = jsonData.getString("patient_id");
        final String patientName= jsonData.getString("patient_name");
        if (null == reservationId || StringUtils.isBlank(patientId) || StringUtils.isBlank(patientName))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无reservation_id、patient_id、patient_name节点！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String doctorName = sessionMap.get("authorName").toString();  //下约医生。

        return new ResultModel<>(reserveService.makeMachineReservation(reservationId, patientId, patientName, doctorName));
    }
    @ResponseBody
    @PostMapping("/make_machine_reservation2")
    public ResultModel makeMachineReservation2(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++makeMachineReservation2() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer machineId = jsonData.getInteger("machine_id");
        final String cureDate   = jsonData.getString("cure_date");
        final String cureTime   = jsonData.getString("cure_time");
        final String patientId  = jsonData.getString("patient_id");
        final String patientName= jsonData.getString("patient_name");
        if (null == machineId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无machine_id节点！"));
        }
        if (StringUtils.isBlank(cureDate) || StringUtils.isBlank(cureTime) || StringUtils.isBlank(patientId) || StringUtils.isBlank(patientName))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无cure_date、cure_time、patient_id、patient_name节点！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String doctorName = sessionMap.get("authorName").toString();  //下约医生。

        return new ResultModel<>(reserveService.makeMachineReservation2(machineId, cureDate, cureTime, patientId, patientName, doctorName));
    }

    /**
     * 治疗仪取消预约。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/cancel_machine_reservation")
    public ResultModel canelMachineReservation(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++canelMachineReservation() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer reservationId = jsonData.getInteger("reservation_id");
        if (null == reservationId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无reservation_id节点！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String doctorName = sessionMap.get("authorName").toString();  //下约医生。

        return new ResultModel<>(reserveService.cancelMachineReservation(reservationId, doctorName));
    }
    @ResponseBody
    @PostMapping("/cancel_machine_reservation2")
    public ResultModel canelMachineReservation2(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++canelMachineReservation2() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer machineId = jsonData.getInteger("machine_id");
        final String cureDate   = jsonData.getString("cure_date");
        final String cureTime   = jsonData.getString("cure_time");
        if (null == machineId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无machine_id节点！"));
        }
        if (StringUtils.isBlank(cureDate) || StringUtils.isBlank(cureTime))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无cure_date、cure_time节点！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String doctorName = sessionMap.get("authorName").toString();  //下约医生。

        return new ResultModel<>(reserveService.cancelMachineReservation2(machineId, cureDate, cureTime, doctorName));
    }

    /**
     * 查询患者的预约清单。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/query_patient_reservation")
    public ResultModel queryReservationByPat(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryReservationByPat() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String patientId = jsonData.getString("patient_id");
        if (StringUtils.isBlank(patientId))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无patient_id节点！"));
        }

        return new ResultModel<>(reserveService.queryReservationByPat(patientId));
    }

    /**
     * 查询所有治疗仪的预约表格。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_machine_reservation_table")
    public ResultModel queryMachineScheduleTable(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryMachineScheduleTable() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        return new ResultModel<>(reserveService.queryMachineReseTable());
    }

    /**
     * 查询某台治疗仪的已预约情况。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_machine_reserved")
    public ResultModel queryMachineReserved(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryMachineReserved() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer machineId = jsonData.getInteger("machine_id");
        if (null == machineId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无machine_id节点！"));
        }

        return new ResultModel<>(reserveService.queryMachineReserved(machineId));
    }

    /**
     * 查询某台治疗仪的今天的已预约情况。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_machine_reserved_today")
    public ResultModel queryMachineReservedToday(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryMachineReservedToday() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer machineId = jsonData.getInteger("machine_id");
        if (null == machineId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无machine_id节点！"));
        }

        return new ResultModel<>(reserveService.queryMachineReservedToday(machineId));
    }


    /**
     * 查询某个治疗师的排班。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_curer_schedule_table")
    public ResultModel queryCurerScheduleTable(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryCurerScheduleTable() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String auAccountUsername  = sessionMap.get("loginId").toString();  //登录手机号。

        return new ResultModel<>(reserveService.queryCurerSchedule(auAccountUsername));
    }

    /**
     * 设定治疗师的工作日。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/set_curer_workday")
    public ResultModel setCurerWorkday(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++setCurerWorkday() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer scheduleId    = jsonData.getInteger("schedule_id");
        if (null == scheduleId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无schedule_id节点！"));
        }
        final String amorpm = jsonData.getString("am_pm");
        if (StringUtils.isBlank(amorpm))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无am_pm节点！"));
        }

        return new ResultModel<>(reserveService.setWorkday(scheduleId, amorpm));
    }
    @ResponseBody
    @PostMapping("/set_curer_holiday")
    public ResultModel setCurerHoliday(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++setCurerHoliday() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer scheduleId    = jsonData.getInteger("schedule_id");
        if (null == scheduleId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无schedule_id节点！"));
        }
        final String amorpm = jsonData.getString("am_pm");
        if (StringUtils.isBlank(amorpm))    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无am_pm节点！"));
        }

        return new ResultModel<>(reserveService.setHoliday(scheduleId, amorpm));
    }

    /**
     * 查询某一天某个项目的可约治疗师。
     * 如果该日某治疗师修改，则她不会出现在列表中。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_curer_list")
    public ResultModel queryCurerList(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryCurerList() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer prjId     = jsonData.getInteger("prj_id");
        final String cureDate   = jsonData.getString("cure_date");
        if (null == prjId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无治疗项目prj_id节点！"));
        }
        if (StringUtils.isBlank(cureDate))  {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无治疗日期cure_date节点！"));
        }

        return new ResultModel<>(reserveService.queryCurerList(prjId, cureDate));
    }

    /**
     * 获取治疗师的空闲时段。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/get_curer_idle")
    public ResultModel queryCurerIdle(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryCurerIdle() begin, arg:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final Integer prjId     = jsonData.getInteger("prj_id");
        final String cureDate   = jsonData.getString("cure_date");
        final Integer curerId   = jsonData.getInteger("curer_id");
        if (null == prjId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无治疗项目prj_id节点！"));
        }
        if (StringUtils.isBlank(cureDate))  {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无治疗日期cure_date节点！"));
        }
        if (null == curerId)    {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无治疗师curer_id节点！"));
        }

        return new ResultModel<>(reserveService.queryCurerIdle(cureDate, curerId, prjId));
    }

}
